package com.cat.testviews;

import java.io.File;
import java.io.IOException;

import android.app.Activity;
import android.app.Notification;
import android.app.PendingIntent;
import android.content.Intent;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.widget.Button;
import android.widget.SeekBar;

public class MainActivity extends Activity implements
		MediaPlayer.OnPreparedListener, MediaPlayer.OnCompletionListener,
		SeekBar.OnSeekBarChangeListener {
	static final String TEG = "testviews";
	static final int PROGRESS_MAX = 100;

	private int currentPlaySong;

	// there status indicates where there progressBar's cursor
	private int progressStatus;
	private Boolean onPlayingMusic;
	private File musicFiles[];
	private MediaPlayer mediaPlayer = null;
	private SeekBar progressBar = null;
	private Handler mHandler = new Handler();
	private ProgressThread progressThread = null;
	private Boolean stopThread = true;
	private Boolean getDurationTime = true;
	private Boolean isMovingSeekBar = false;
	private Boolean isPreparing = false;

	private int durationTime;
	private int currentTime;

	private class ProgressThread extends Thread {
		public ProgressThread() {
			super();
		}

		@Override
		public void run() {
			// TODO Auto-generated method stub
			super.run();
			
			int progressMax = PROGRESS_MAX;
			while (!stopThread) {
				
				if (getDurationTime || durationTime == 0) {
					durationTime = mediaPlayer.getDuration();
					getDurationTime = false;
				}
				
				currentTime = mediaPlayer.getCurrentPosition();
				progressStatus = currentTime * progressMax / durationTime;
				if (progressStatus > progressMax)
					break;
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub
						progressBar.setProgress(progressStatus);
					}
				});

			}
			
			if (isMovingSeekBar) {
				isMovingSeekBar = false;
			} else {
				mHandler.post(new Runnable() {

					@Override
					public void run() {
						// TODO Auto-generated method stub

						mediaPlayer.release();
						mediaPlayer = null;
						progressThread = null;
					}
				});
			}
		}

	}

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		File musicFile = getMusicDirectory();
		musicFiles = musicFile.listFiles();
		progressStatus = 0;
		currentPlaySong = 0;
		durationTime = 0;
		currentTime = 0;
		onPlayingMusic = false;

		progressBar = (SeekBar) findViewById(R.id.seekBar1);
		progressBar.setOnSeekBarChangeListener(this);
		
	}

	private File getMusicDirectory() {
		File file = new File(
				android.os.Environment.getExternalStorageDirectory(), "Music");
		return file;
	}

	public void play(View view) {
		// start play music
		Button playButton = (Button) view;
		if (onPlayingMusic) {
			playButton.setText(R.string.play);
			stopMusic();
		} else {
			playButton.setText(R.string.stop);
			playMusic();
		}
	}

	// 尝试比较内容
	public void next(View view) {

		// if there no player,need to create one here;
		// we need to reset the player here anyhow;
		
		if (isPreparing)
			return;

		currentPlaySong++;
		if (currentPlaySong >= musicFiles.length)
			currentPlaySong = 0;
		progressStatus = 0;

		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			mediaPlayer.reset();
			setPlayerWihtCurrentSong();
			isPreparing = true;
			mediaPlayer.prepareAsync();
		} else {
			// 当不是正在播放音乐是点击next
			currentTime = 0;
		}
	}

	private void setPlayerWihtCurrentSong() {
		if (mediaPlayer == null)
			getNewMediaPlayer();
		mediaPlayer.reset();
		Uri currentPlayUri = Uri.fromFile(musicFiles[currentPlaySong]);
		try {
			mediaPlayer.setDataSource(getApplicationContext(), currentPlayUri);
		} catch (IllegalArgumentException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (SecurityException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IllegalStateException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	private void getNewMediaPlayer() {
		// create a new mediaPlayer

		if (mediaPlayer == null) {
			mediaPlayer = new MediaPlayer();
			mediaPlayer.setOnPreparedListener(this);
			mediaPlayer.setOnCompletionListener(this);
			mediaPlayer.setAudioStreamType(AudioManager.STREAM_MUSIC);
		}
	}

	private void playMusic() {

		if (mediaPlayer == null) {
			getNewMediaPlayer();
			setPlayerWihtCurrentSong();
			isPreparing = true;
			mediaPlayer.prepareAsync();
		} else {
			// 进入playMusic要么是第一次启动后点击play，要么是点击stop后点击
			// play，两种情况下，mediaPlayer都是为null的，如果不是，直接返回

			return;
		}

//		PendingIntent pi = PendingIntent.getActivity(getApplicationContext(),
//				0, new Intent(getApplicationContext(), MainActivity.class),
//				PendingIntent.FLAG_UPDATE_CURRENT);
//		Notification notification = new Notification();
//		notification.icon = R.drawable.ic_launcher_shortcut_music_playlist;
//		notification.flags |= Notification.FLAG_ONGOING_EVENT;
//		notification.setLatestEventInfo(getApplicationContext(), "TestViews",
//				"Playing:", pi);
	}

	@Override
	public void onPrepared(MediaPlayer mp) {
		// TODO Auto-generated method stub
		
		if (progressThread != null) {
			// 由点击next，且正在播放音乐情况下进入到prepare状态

			mediaPlayer.start();
			getDurationTime = true;
			onPlayingMusic = true;
			stopThread = false;
		} else {
			// 由点击play后进入到prepare状态,可能是第一次启动，也可能是点击stop之后
			// 再点击play

			mediaPlayer.seekTo(currentTime);
			mediaPlayer.start();
			onPlayingMusic = true;
			stopThread = false;
			progressThread = new ProgressThread();
			progressThread.start();
		}
		
		isPreparing = false;
	}

	private void stopMusic() {
		stopThread = true;
		onPlayingMusic = false;
	}

	@Override
	public void onCompletion(MediaPlayer mp) {
		// TODO Auto-generated method stub

		currentPlaySong++;
		if (currentPlaySong >= musicFiles.length)
			currentPlaySong = 0;
		progressStatus = 0;

		if (mediaPlayer == null)
			getNewMediaPlayer();
		mediaPlayer.reset();
		setPlayerWihtCurrentSong();
		isPreparing = true;
		mediaPlayer.prepareAsync();
		
	}
	
	@Override
	public void onProgressChanged(SeekBar seekBar, int progress,
			boolean fromUser) {
		// TODO Auto-generated method stub

	}

	@Override
	public void onStartTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

		if (mediaPlayer != null && mediaPlayer.isPlaying()) {
			stopThread = true;
			isMovingSeekBar = true;
		}
	}

	@Override
	public void onStopTrackingTouch(SeekBar seekBar) {
		// TODO Auto-generated method stub

		if (mediaPlayer != null && mediaPlayer.isPlaying()) {

			int progress = seekBar.getProgress();
			int progressMax = PROGRESS_MAX;
			int tempCurrentTime = progress * durationTime / progressMax;
			mediaPlayer.seekTo(tempCurrentTime);
			mediaPlayer.start();

			stopThread = false;
			progressThread = new ProgressThread();
			progressThread.start();
		} else {

		}
	}
}
